use super::r#type::TYPE_CACHE;
use network_scanner_server_model::RecordTypeId;
use rocket_db_pools::sqlx::{self, sqlite::SqliteRow, Row, Sqlite, Transaction};

pub async fn count_all_records<'a>(db: &mut Transaction<'a, Sqlite>) -> Result<u32, sqlx::Error> {
    sqlx::query("SELECT COUNT(id) FROM main")
        .try_map(|row: SqliteRow| row.try_get(0))
        .fetch_one(&mut **db)
        .await
}

pub async fn count_records<'a>(
    db: &mut Transaction<'a, Sqlite>,
    type_id: RecordTypeId,
) -> Result<Option<u32>, sqlx::Error> {
    let cache = TYPE_CACHE.read().await;
    let cache = cache.as_ref().expect("Cache is not initialized");
    let cache = match cache.get(&type_id) {
        Some(cache) => cache,
        None => return Ok(None),
    };

    Ok(Some(
        sqlx::query(cache.count.as_str())
            .try_map(|row: SqliteRow| row.try_get(0))
            .fetch_one(&mut **db)
            .await?,
    ))
}
